package com.xiongjie.circuitBreaker;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.client.HttpResponse;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;

public class CircuitBreakerVertxBaseHandler extends AbstractVerticle {

    @Override
    public void start(){
        Router router = Router.router(vertx);
        WebClient client = WebClient.create(vertx, new WebClientOptions()
                .setDefaultHost("localhost")
                .setDefaultPort(8888));
        router.get("/").handler(ar ->{
           ar.response().end("hello,world");
        });
        router.get("/proxy").handler(rc -> {
            HttpRequest<Buffer> toReq = client.request(HttpMethod.GET, "http://localhost:8888/");
            Handler<AsyncResult<HttpResponse<Buffer>>> responseHandler = ar -> {
                HttpResponse response = ar.result();
                HttpServerResponse toRsp = rc.response();

                if (ar.succeeded()) {
                    toRsp.setStatusCode(response.statusCode());
                    toRsp.headers().setAll(response.headers());

                    if (response.body() == null) {
                        System.out.println("no body");
                        toRsp.end("no body");
                    } else {
                        System.out.println("has body");
                        toRsp.end("has body");
                    }
                } else {
                    System.out.println("服务没启动");
                    toRsp.setStatusCode(502).end(ar.cause().getMessage());
                }
            };
            toReq.send(responseHandler);
        });

        vertx.createHttpServer()
                .requestHandler(router)
                .listen(8888, result -> {
                    if (result.succeeded()) {
                        System.out.println("有请求："+result.toString());
                    } else {
                        System.out.println("请求失败："+result.toString());
                    }
                });
    }
}
